<template>
  <div>
    <el-dialog :title="`批次管理试纸名称:${title}`"
               :visible.sync="batchDialog.show"
               center
               @close="$emit('closedialog')"
               width="70%">
      <el-button type="primary"
                 style="margin-bottom: 20px"
                 @click="handleOption(null, 'add')">新 增</el-button>
      <!-- 荧光/胶体金试纸 -->
      <el-table border
                :data="tableList"
                v-if="batchDialog.object.testStripFactoryDto.testStripTypeId === 3 || batchDialog.object.testStripFactoryDto.testStripTypeId === 5">
        <el-table-column prop="productionDate"
                         label="生产日期"
                         width="150"></el-table-column>
        <el-table-column prop="expirationDate"
                         label="有效期"
                         width="150"></el-table-column>
        <el-table-column prop="batchNumber"
                         label="批号"></el-table-column>
        <el-table-column prop="count"
                         label="数量"
                         width="80"></el-table-column>
        <el-table-column prop="packagingBarcode"
                         label="包装条码"></el-table-column>
        <el-table-column prop="packingSpecification"
                         label="包装规格"
                         width="80"></el-table-column>
        <el-table-column prop="accessoriesContent"
                         label="配件内容"></el-table-column>
        <el-table-column prop="barcode"
                         label="试纸条码"></el-table-column>
        <el-table-column prop="codeFileUrl"
                         label="code码">
          <template slot-scope="scope">
            <el-button size="mini"
                       type="text"
                       icon="el-icon-download"
                       @click="download(scope.row)">下载</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="300">
          <template slot-scope="scope">
            <el-button type="primary"
                       size="mini"
                       @click="handleOption(scope.row, 'edit')">编 辑</el-button>
            <el-button size="mini"
                       type="success"
                       @click="viewBarcode(scope.row)">查看条形码
            </el-button>
            <el-button type="danger"
                       size="mini"
                       @click="handleOption(scope.row, 'del')">删 除</el-button>
          </template>
        </el-table-column>
        <el-dialog width="30%"
                   :title="secondTitle"
                   :visible.sync="innerVisible"
                   append-to-body>
          <el-form :model="ruleForm"
                   :rules="rules"
                   ref="ruleFormRef"
                   label-width="100px">
            <el-form-item label="生产日期"
                          prop="productionDate">
              <el-date-picker v-model="ruleForm.productionDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              class="w-220"
                              placeholder="选择生产日期"
                              :picker-options="pickerOptionsStart">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="有效期"
                          prop="expirationDate">
              <el-date-picker v-model="ruleForm.expirationDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              class="w-220"
                              placeholder="选择有效期"
                              :picker-options="pickerOptionsEnd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="批号"
                          prop="batchNumber">
              <el-input v-model="ruleForm.batchNumber"
                        placeholder="请填写批号"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="数量"
                          prop="count">
              <el-input v-model="ruleForm.count"
                        placeholder="请填写数量"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="包装条码"
                          prop="packagingBarcode">
              <el-input v-model="ruleForm.packagingBarcode"
                        placeholder="请填写包装条码"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="包装规格"
                          prop="packingSpecification">
              <el-input v-model="ruleForm.packingSpecification"
                        placeholder="请填写包装规格"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="配件内容"
                          prop="accessoriesContent">
              <el-input type="textarea"
                        v-model="ruleForm.accessoriesContent"
                        placeholder="请填写配件内容"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="试纸条码"
                          prop="barcode">
              <el-input v-model="ruleForm.barcode"
                        placeholder="请填写试纸条码"
                        class="w-220"></el-input>
            </el-form-item>

            <el-form-item label="code码">
              <el-upload :action="fileUploadAction"
                         :on-success="uploadSuccess"
                         :limit="1">
                <el-button size="small"
                           type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item label="code码名字">
              <el-input v-model="ruleForm.codeFileName"
                        :disabled="true"
                        placeholder="请上传code码"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary"
                         @click="submitForm">提 交</el-button>
              <el-button @click="innerVisible = false">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-table>
      <!-- 干化学试纸、电化学试纸 -->
      <el-table border
                :data="tableList"
                v-else>
        <el-table-column prop="productionDate"
                         label="生产日期"
                         width="150"></el-table-column>
        <el-table-column prop="expirationDate"
                         label="有效期"
                         width="150"></el-table-column>
        <el-table-column prop="batchNumber"
                         label="批号"></el-table-column>
        <el-table-column prop="count"
                         label="数量"
                         width="80"></el-table-column>
        <el-table-column prop="packagingBarcode"
                         label="包装条码"></el-table-column>
        <el-table-column prop="packingSpecification"
                         label="包装规格"
                         width="80"></el-table-column>
        <el-table-column prop="barcode"
                         label="code码"></el-table-column>
        <el-table-column label="操作"
                         width="300">
          <template slot-scope="scope">
            <el-button type="primary"
                       size="mini"
                       @click="handleOption(scope.row, 'edit')">编 辑</el-button>
            <el-button size="mini"
                       type="success"
                       @click="viewBarcode(scope.row)">查看条形码
            </el-button>
            <el-button type="danger"
                       size="mini"
                       @click="handleOption(scope.row, 'del')">删 除</el-button>
          </template>
        </el-table-column>
        <el-dialog width="30%"
                   :title="secondTitle"
                   :visible.sync="innerVisible"
                   append-to-body>
          <el-form :model="ruleForm"
                   :rules="rules"
                   ref="ruleFormRef"
                   label-width="100px">
            <el-form-item label="生产日期"
                          prop="productionDate">
              <el-date-picker v-model="ruleForm.productionDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              class="w-220"
                              placeholder="选择生产日期"
                              :picker-options="pickerOptionsStart">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="有效期"
                          prop="expirationDate">
              <el-date-picker v-model="ruleForm.expirationDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              class="w-220"
                              placeholder="选择有效期"
                              :picker-options="pickerOptionsEnd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="批号"
                          prop="batchNumber">
              <el-input v-model="ruleForm.batchNumber"
                        placeholder="请填写批号"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="数量"
                          prop="count">
              <el-input v-model="ruleForm.count"
                        placeholder="请填写数量"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="包装条码"
                          prop="packagingBarcode">
              <el-input v-model="ruleForm.packagingBarcode"
                        placeholder="请填写包装条码"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="包装规格"
                          prop="packingSpecification">
              <el-input v-model="ruleForm.packingSpecification"
                        placeholder="请填写包装规格"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="配件内容"
                          prop="accessoriesContent"
                          v-if="batchDialog.object.testStripFactoryDto.testStripTypeId===3">
              <el-input type="textarea"
                        v-model="ruleForm.accessoriesContent"
                        placeholder="请填写配件内容"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="试纸条码"
                          prop="barcode"
                          v-if="batchDialog.object.testStripFactoryDto.testStripTypeId===3">
              <el-input v-model="ruleForm.barcode"
                        placeholder="请填写试纸条码"
                        class="w-220"></el-input>
            </el-form-item>
            <el-form-item label="code码"
                          prop="barcode"
                          v-if="batchDialog.object.testStripFactoryDto.testStripTypeId !== 3">
              <el-input v-model="ruleForm.barcode"
                        placeholder="请填写code码"
                        class="w-220"></el-input>
            </el-form-item>

            <el-form-item label="code码"
                          v-if="batchDialog.object.testStripFactoryDto.testStripTypeId===3">
              <el-upload :action="fileUploadAction"
                         :on-success="uploadSuccess"
                         :limit="1">
                <el-button size="small"
                           type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>

            <el-form-item>
              <el-button type="primary"
                         @click="submitForm">提 交</el-button>
              <el-button @click="innerVisible = false">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </el-table>

    </el-dialog>
    <el-dialog title="打印条形码"
               :visible.sync="dialogVisible"
               width="30%">
      <div id="printArea"
           style="width: 100%; text-align: center">
        <img id="barcode" />
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
        <el-button type="primary"
                   v-print="'#barcode'">打印</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import JsBarcode from "jsbarcode";
  export default {
    props: ['batchDialog'],
    fileUploadAction: null,
    data () {
      const dialogTitle = this.batchDialog.object.name;
      return {
        title: dialogTitle,
        tableList: [],
        innerVisible: false,
        ruleForm: {
          codeFileName: '',
        },
        rules: {
          productionDate: [
            { type: 'string', required: true, message: '选择生产日期', trigger: 'change' }
          ],
          expirationDate: [
            { type: 'string', required: true, message: '选择有效期', trigger: 'change' }
          ],
          batchNumber: [
            { required: true, message: '请填写批号', trigger: 'blur' }
          ],
          count: [
            { required: true, message: '请填写数量', trigger: 'blur' }
          ],
          packagingBarcode: [
            { required: true, message: '请填写包装条码', trigger: 'blur' }
          ],
          packingSpecification: [
            { required: true, message: '请填写包装规格', trigger: 'blur' }
          ],
          accessoriesContent: [
            { required: true, message: '请填写配件内容', trigger: 'blur' }
          ],
          barcode: [
            { required: true, message: '请填写试纸条码', trigger: 'blur' }
          ],
        },
        fileUploadAction: this.api.appUpgradeUpload.url,
        saveParams: {},
        secondTitle: '',
        dialogVisible: false,
        pickerOptionsStart: {
          disabledDate: time => {
            const endDateVal = new Date(this.ruleForm.expirationDate).getTime()
            if (endDateVal) {
              return time.getTime() > endDateVal - 0
            }
          }
        },
        pickerOptionsEnd: {
          disabledDate: time => {
            const beginDateVal = new Date(this.ruleForm.productionDate).getTime();
            if (beginDateVal) {
              return time.getTime() < beginDateVal - 0
            }
          }
        }
      }
    },
    methods: {
      // 查询批次管理
      async getTestStripBatch () {
        let resData = this.batchDialog.object;
        let params = {
          testStripId: resData.id,
          testStripFactoryId: resData.testStripFactoryDto.id
        }
        this.saveParams = params;
        const { data: res } = await this.post(this.api.testStrip.getTestStripBatch, params);
        if (res.code === '200') {
          this.tableList = res.object;
        }
      },

      // 操作
      async handleOption (row, op) {

        switch (op) {
          case 'add':
            this.innerVisible = true;
            this.secondTitle = '新 增'
            let arr = Object.keys(this.$refs);
            if (arr.length > 0) {
              this.$refs['ruleFormRef'].resetFields();
              this.ruleForm = Object.assign({}, row)
            }
            break
          case 'edit':
            this.innerVisible = true;
            this.secondTitle = '编 辑';
            this.ruleForm = Object.assign({}, row);
            break
          case 'del':
            this.$confirm('确认删除？')
              .then(async _ => {
                row.isDelete = 1;
                this.ruleForm = row;
                const { data: res } = await this.handleOp();
                if (res.code === '200') {
                  this.$message.success('删除成功');
                  this.getTestStripBatch();
                }
              })
              .catch(_ => { });
            break
        }
      },
      // 增加、删除、编辑公共接口
      handleOp () {
        let newArr = [];
        newArr.push({ ...this.ruleForm });
        let { testStripFactoryId, testStripId } = this.saveParams;
        return this.post(this.api.testStrip.uploadTestStripBatch, {
          testStripBatchDtoList: newArr,
          id: testStripFactoryId,
          testStripId: testStripId
        })
      },

      // 提交
      submitForm () {
        this.$refs['ruleFormRef'].validate(async (valid) => {
          if (valid) {
            const { data: res } = await this.handleOp();
            if (res.code === '200') {
              this.$message.success('保存成功');
              this.getTestStripBatch();
              this.innerVisible = false;
            }
          }
        });
      },
      createBarcode (code) {
        JsBarcode("#barcode", code, {
          format: "CODE128", //条形码的格式
          lineColor: "#000", //线条颜色
          width: 2, //线宽
          height: 50, //条码高度
          displayValue: true //是否显示文字信息
        });
      },
      // 查看条形码
      viewBarcode (row) {
        this.dialogVisible = true;
        let vm = this;
        setTimeout(function () {
          vm.createBarcode(row.barcode);
        }, 100);
      },
      // 上传成功
      uploadSuccess (response, file, fileList) {
        if (response.code === '200') {
          // 状态码为200时则上传成功
          this.ruleForm.codeFileUrl = file.response.object[0];
          this.$set(this.ruleForm, 'codeFileName', file.name);
          this.$message.success('上传成功');
        } else {
          // 状态码不是200时上传失败 从列表中删除
          fileList.splice(fileList.indexOf(file), 1);
          this.$message.error(response.message);
        }
      },
      // 文件下载
      download (row) {
        if (row.codeFileUrl) {
          let fileUrl = row.codeFileUrl;
          let fileName = row.barcode;
          let fileFormat = fileUrl.split('.').includes('txt');
          if (fileFormat) {
            const xmlhttp = new XMLHttpRequest();
            xmlhttp.addEventListener("load", (response) => {
              let _a = document.createElement('a');
              _a.style.display = 'none';
              _a.download = fileName; // 文件名称
              _a.href = "data:text/plain;charset=utf-8," + encodeURIComponent(response.target.responseText);
              document.body.appendChild(_a);
              _a.click();
              document.body.removeChild(_a);
            })
            xmlhttp.open('GET', fileUrl);
            xmlhttp.send();
          } else {
            const a = document.createElement('a');
            a.setAttribute('download', fileName);
            a.setAttribute('target', '_blank');
            a.setAttribute('href', fileUrl);
            a.click();
          }
        } else {
          this.$message.error('没有文件可下载!');
        }
      },
    },
    created () {
      this.getTestStripBatch();
    },
  }
</script>
<style lang="scss" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .w-220 {
    width: 200px;
  }
</style>
